<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能文字识别系统</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.1/css/bootstrap.min.css" rel="stylesheet">
    <!-- 自定义样式 -->
    <style>
        body {
            background-color: #f8f9fa;
            font-family: 'Microsoft YaHei', sans-serif;
        }
        .container {
            max-width: 800px;
        }
        .card {
            border-radius: 6px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
            margin-bottom: 20px;
            border: none;
        }
        .card-header {
            background-color: #f8f9fa;
            color: #212529;
            font-weight: 600;
            border-bottom: 1px solid #eaeaea;
            padding: 12px 16px;
        }
        .preview-image {
            max-width: 100%;
            max-height: 400px;
            margin: 10px auto;
            display: block;
            border-radius: 4px;
        }
        .loading {
            display: none;
            text-align: center;
            padding: 20px;
        }
        .drop-zone {
            border: 2px dashed #dee2e6;
            border-radius: 6px;
            padding: 30px 20px;
            text-align: center;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        .drop-zone:hover {
            border-color: #6c757d;
            background-color: rgba(0,0,0,0.01);
        }
        .confidence {
            color: #28a745;
            font-size: 0.9rem;
        }
        .btn-primary {
            background-color: #0d6efd;
            border-color: #0d6efd;
        }
        .btn-warning {
            background-color: #fd7e14;
            border-color: #fd7e14;
        }
        .btn-success {
            background-color: #198754;
            border-color: #198754;
        }
        .action-buttons {
            display: flex;
            justify-content: center;
            gap: 10px;
            margin: 20px 0;
            padding: 15px;
            background-color: #fff;
            border-radius: 6px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
        }
        .action-buttons > * {
            flex: 1;
            min-width: 0;
        }
        .action-buttons .btn {
            white-space: nowrap;
            padding: 8px 16px;
        }
        .action-buttons select {
            max-width: 150px;
        }
        .text-result {
            padding: 10px;
            margin-bottom: 10px;
            border-radius: 4px;
            background-color: #fff;
            border-left: 3px solid #0d6efd;
        }
        .alert {
            border-radius: 4px;
        }
        /* 语言选择下拉框样式 */
        #langSelect {
            min-width: 120px;
            height: 38px;
            border-radius: 4px;
            border: 1px solid #ced4da;
            padding: 0.375rem 1.75rem 0.375rem 0.75rem;
            font-size: 1rem;
            font-weight: 400;
            line-height: 1.5;
            color: #212529;
            background-color: #fff;
            cursor: pointer;
        }
        #langSelect:focus {
            border-color: #86b7fe;
            outline: 0;
            box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
        }
        #showSelect {
            min-width: 150px;
            height: 38px;
            border-radius: 4px;
            border: 1px solid #ced4da;
            padding: 0.375rem 1.75rem 0.375rem 0.75rem;
            font-size: 1rem;
            font-weight: 400;
            line-height: 1.5;
            color: #212529;
            background-color: #fff;
            cursor: pointer;
        }
        #showSelect:focus {
            border-color: #86b7fe;
            outline: 0;
            box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
        }
    </style>
</head>
<body>
    <div class="container mt-4 mb-5">
        <h2 class="text-center mb-4">智能文字识别系统</h2>
        
        <!-- 主要内容区 -->
        <div class="row">
            <div class="col-md-12">
                <!-- 上传区域 -->
                <div class="card">
                    <div class="card-header">图片上传</div>
                    <div class="card-body">
                        <div class="drop-zone" id="dropZone" onclick="document.getElementById('fileInput').click()">
                            <p class="mb-0">点击或拖拽图片到此处上传</p>
                            <input type="file" id="fileInput" accept="image/*" style="display: none" onchange="handleFileSelect(event)">
                        </div>
                    </div>
                </div>
                
                <!-- 操作按钮 -->
                <div class="action-buttons">
                    <button class="btn btn-primary" onclick="processImage('ocr')">普通文字识别</button>
                    <button class="btn btn-warning" onclick="processImage('handwriting')">手写体识别</button>
                    <button class="btn btn-success" onclick="processImage('draw')">可视化结果</button>
                    <!-- 添加语言选择下拉框 -->
                    <select class="form-select" id="langSelect" style="width: auto;">
                        <option value="ch">中文识别</option>
                        <option value="en">英文识别</option>
                    </select>
                    <!-- 添加展示图片选择下拉框 -->
                    <select class="form-select" id="showSelect" style="width: auto;">
                        <option value="base64">展示识别图片</option>
                        <option value="none">不展示识别图片</option>
                    </select>
                </div>

                <!-- 加载提示 -->
                <div id="loading" class="loading">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">加载中...</span>
                    </div>
                    <p class="mt-2">处理中，请稍候...</p>
                </div>

                <!-- 预览区域 -->
                <div id="previewContainer" style="display: none;" class="card">
                    <div class="card-header">原始图片</div>
                    <div class="card-body text-center">
                        <img id="preview" class="preview-image">
                    </div>
                </div>

                <!-- 结果展示区域 -->
                <div id="resultContainer" class="card" style="display: none;">
                    <div class="card-header">
                        <span id="resultTitle">识别结果</span>
                    </div>
                    <div class="card-body">
                        <div id="resultContent"></div>
                    </div>
                </div>

                <!-- 可视化结果展示 -->
                <div id="visualContainer" class="card" style="display: none;">
                    <div class="card-header">可视化结果</div>
                    <div class="card-body text-center">
                        <img id="visualResult" class="preview-image">
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.1/js/bootstrap.bundle.min.js"></script>
    
    <script>
        // 拖拽上传
        const dropZone = document.getElementById('dropZone');
        
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            dropZone.addEventListener(eventName, preventDefaults, false);
        });

        function preventDefaults (e) {
            e.preventDefault();
            e.stopPropagation();
        }

        ['dragenter', 'dragover'].forEach(eventName => {
            dropZone.addEventListener(eventName, highlight, false);
        });

        ['dragleave', 'drop'].forEach(eventName => {
            dropZone.addEventListener(eventName, unhighlight, false);
        });

        function highlight(e) {
            dropZone.classList.add('border-primary');
            dropZone.style.backgroundColor = 'rgba(13, 110, 253, 0.05)';
        }

        function unhighlight(e) {
            dropZone.classList.remove('border-primary');
            dropZone.style.backgroundColor = '';
        }

        dropZone.addEventListener('drop', handleDrop, false);

        function handleDrop(e) {
            const dt = e.dataTransfer;
            const files = dt.files;
            handleFiles(files);
        }

        // 文件选择处理
        function handleFileSelect(event) {
            handleFiles(event.target.files);
        }

        function handleFiles(files) {
            if (files.length > 0) {
                const file = files[0];
                if (file.type.startsWith('image/')) {
                    // 预览图片
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        document.getElementById('preview').src = e.target.result;
                        document.getElementById('previewContainer').style.display = 'block';
                        // 清空之前的结果
                        document.getElementById('resultContainer').style.display = 'none';
                        document.getElementById('visualContainer').style.display = 'none';
                    }
                    reader.readAsDataURL(file);
                } else {
                    alert('请选择图片文件！');
                }
            }
        }

        // 处理图片
        async function processImage(type) {
            const preview = document.getElementById('preview');
            if (!preview.src) {
                alert('请先选择图片！');
                return;
            }

            // 显示加载提示
            document.getElementById('loading').style.display = 'block';

            try {
                // 准备图片数据
                const base64Data = preview.src.split(',')[1];
                let endpoint;
                
                // 根据类型选择不同的接口
                switch(type) {
                    case 'ocr':
                        endpoint = 'ocr_system';
                        break;
                    case 'handwriting':
                        endpoint = 'handwriting';
                        break;
                    case 'draw':
                        endpoint = 'draw_ocr';
                        break;
                }
                
                // 发送请求
                const response = await fetch(`http://localhost:9000/predict/${endpoint}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        images: [base64Data],
                        output_type: document.getElementById('showSelect').value,
                        lang: document.getElementById('langSelect').value
                    })
                });

                const result = await response.json();

                if (result.status === '000') {
                    showResult(result.results[0], type);
                } else {
                    throw new Error(result.msg || '处理失败');
                }
            } catch (error) {
                alert('处理失败：' + error.message);
            } finally {
                // 隐藏加载提示
                document.getElementById('loading').style.display = 'none';
            }
        }

        // 统一的结果显示函数
        function showResult(result, type) {
            // 获取所需的DOM元素
            const visualContainer = document.getElementById('visualContainer');
            const resultContainer = document.getElementById('resultContainer');
            const visualImage = document.getElementById('visualResult');
            const content = document.getElementById('resultContent');
            const titleElement = document.getElementById('resultTitle');
            const lang = document.getElementById('langSelect').value;
            
            // 1. 设置标题
            const langPrefix = lang === 'ch' ? '中文' : '英文';
            let typeText = '';
            switch(type) {
                case 'handwriting':
                    typeText = '手写体';
                    break;
                case 'draw':
                    typeText = '可视化';
                    break;
                default:
                    typeText = '普通文字';
            }
            titleElement.textContent = `${langPrefix}${typeText}识别结果`;
            
            // 2. 处理图片显示
            if (result && result.image) {
                visualImage.src = 'data:image/jpeg;base64,' + result.image;
                visualContainer.style.display = 'block';
            } else {
                visualContainer.style.display = 'none';
            }
            
            // 3. 处理文字结果显示
            // 仅当不是纯可视化结果时显示文字结果
            if (type !== 'draw') {
                if (!result || !result.results || result.results.length === 0) {
                    // 无识别结果时显示提示信息
                    content.innerHTML = '<div class="alert alert-warning" role="alert">' + 
                        (result.message || '未检测到文字') + '</div>';
                } else {
                    // 有识别结果时显示详细内容
                    const html = result.results.map(item => `
                        <div class="text-result">
                            <div class="fw-bold">${item.text}</div>
                            <div class="confidence mt-1">置信度: ${(item.confidence * 100).toFixed(2)}%</div>
                        </div>
                    `).join('');
                    content.innerHTML = html;
                }
                resultContainer.style.display = 'block';
            } else {
                // 纯可视化结果时隐藏文字结果区域
                resultContainer.style.display = 'none';
            }
            
            // 4. 特殊情况处理：既无图片也无文字结果时
            if ((!result || (!result.image && (!result.results || result.results.length === 0))) && result.message) {
                visualContainer.style.display = 'none';
                content.innerHTML = `<div class="alert alert-warning" role="alert">${result.message}</div>`;
                resultContainer.style.display = 'block';
            }
        }
    </script>
</body>
</html>
